<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use liliuwei\think\Jump;
use think\db\Fetch;
use think\facade\Db;
use think\facade\View;
use think\Request;

class goods extends BaseController
{
 use Jump;
   //跳转添加页面
    public function create()
    {
        return View::fetch('create');
    }
    //添加功能
    public function adddata(Request $request)
    {
        //接值
        $data=[
            'id'=>$request->param('id'),
            'gname'=>$request->param('gname'),
            'storage'=>$request->param('storage')
        ];
        //文件上传
        $file=$request->file('images');
        if ($file){
            $img=\think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            $data['images']="/storage/".$img;
        }
        //商品名必填验证
        $validate = new \app\validate\goods;
        $result = $validate->check($data);
        if(!$result){
            return json(['code'=>201,'msg'=>$validate->getError()]);
        }
        $res=Db::name('goods')->insert($data);
        //数据保存成功，并且提示
        if ($res){
            $this->success('添加成功','/goods/listdata');
        }else{
            $this->error('添加失败','/goods/create');
        }
    }
    //商品列表展示
    public function listdata(){
       $data=Db::name('goods')->paginate(3);
        return View::fetch('show',['arr'=>$data]);
    }
    //商品编辑信息展示
    public function info(Request $request){
        $g_id=$request->param('g_id');
        $data=Db::name('goods')->where('g_id',$g_id)->find();
        return View::fetch('info',['arr'=>$data]);
}

//商品删除功能
    public function delete(Request $request){
        $g_id=$request->param('g_id');
        $data=Db::name('goods')->where('g_id',$g_id)->delete();
        if ($data){
            $this->success('删除成功','/goods/listdata');
        }else{
            $this->error('删除失败','/goods/listdata');
        }
    }
    //修改
    public  function update(Request $request){
        $g_id=$request->param('g_id');
        $data=[
            'id'=>$request->param('id'),
            'gname'=>$request->param('gname'),
            'storage'=>$request->param('storage')
        ];
        //文件上传
        $file=$request->file('images');
        if ($file){
            $img=\think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            $data['images']="/storage/".$img;
        }
        $res=Db::name('goods')->where('g_id',$g_id)->update($data);
        if ($res){
            $this->success('修改成功','/goods/listdata');
        }else{
            $this->error('修改失败','/goods/info');
        }

    }



}
